﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Areas.WebApi.Controllers;
using HyEduOnline.Entities;
using HyEduOnline.Server.Teacher;
using HyEduOnline.Server.Admin;
using Aspose.Words;
using Aspose.Cells;
using Aspose.Slides;
using System.IO;
namespace WebSite.Areas.WebApi.Controllers
{
    public class TestLibPaperExtController : TestLibPaperController
    {
        private TestLibPaperDAO TLPDao = new TestLibPaperDAO();    //定义TestLibPaperDAO的对象
        private TestPaperStrategyDAO TPSPDao = new TestPaperStrategyDAO();    //定义TestPaperStrategyDAO的对象
        private TestLibPaperDetailDAO TLDDao = new TestLibPaperDetailDAO();    //定义TestLibPaperDetailDAO的对象
        //by lzq
        private TestLibDAO TibDao = new TestLibDAO();
        private TestLibOptionDAO optionDao = new TestLibOptionDAO();
        private const string paperPath = "/Upload/paper/";
        //end

        /// <summary>
        /// 筛选试题卷
        /// </summary>
        /// <param name="firstResult">起始位置</param>
        /// <param name="pagesize">页面大小</param>
        /// <param name="orderBy">排序列</param>
        /// <param name="condition">筛选条件</param>
        /// <returns></returns>
        public Object Search(int firstResult, int pagesize, string orderBy, string condition)
        {

            int totalCount = 0;  //总的数据记录条数
            condition = HttpUtility.UrlDecode(condition);

            IList<TbTestLibPaper> PaperList = TestLibPaperDAO.getByPageDataBase(firstResult, pagesize, orderBy, condition, out totalCount);
            return this.Json(new
            {
                DataCount = totalCount,
                Data = PaperList
            }, JsonRequestBehavior.AllowGet);
        }

        #region 批量删除试卷+DeletePaper
        /// <summary>
        /// DELETE api/TestLibPaper/DeletePaper/?ids="1,2,3,4"
        /// </summary>
        public int DeletePaper(string ids)
        {
            try
            {
                string[] SIds = ids.Split(new char[] { ',' });

                foreach (var SId in SIds)
                {
                    int IId = int.Parse(SId);//对应表的Id

                    TbTestLibPaper Paper = new TestLibPaperDAO().GetByID(IId);//获取到TestLibPaper表Id对应的那条数据
                    if (Paper != null)
                    {
                        
                   

                    string WhereClauseStrategy = "I_PaperID=" + IId;  //add by yzp 10.22

                    TList<TbTestPaperStrategy> TestPaperStrategyList = new TestPaperStrategyDAO().GetByPage(WhereClauseStrategy, 0, int.MaxValue); //获取试卷的所有策略
                    if (TestPaperStrategyList.Count > 0)
                    {
                       

                        foreach (var item in TestPaperStrategyList)
                        {
                            int StrategyID = item.Id;

                            string WhereClauseDetail = "I_StrategyID=" + StrategyID;

                            TList<TbTestLibPaperDetail> TestLibPaperDetailList = new TestLibPaperDetailDAO().GetByPage(WhereClauseDetail, 0, int.MaxValue);  //获取每一个策略下的所有小题
                            if (TestLibPaperDetailList.Count > 0)
                            {
                                foreach (var item1 in TestLibPaperDetailList)
                                {
                                    TLDDao.Del(item1);  //删除每一个小题
                                }
                            }

                            TPSPDao.Del(item);  //删除策略
                        }
 
                    }
                    TLPDao.Del(Paper);
                    }



                }
                return 1;
            }
            catch (Exception ex)
            {

                return 0;
            }
            return 0;
        }
        #endregion




        /// <summary>
        /// 生成试卷模板 并为之生成两个默认的组卷策略 
        /// </summary>

        public JsonResult GenNewPaper(TbTestLibPaper paper)
        {

            TbTestLibPaper TLP = new TbTestLibPaper();   //定义试卷表的对象
            TLP.STestName = paper.STestName;  //获取试卷的名称
            TLP.IKsType = paper.IKsType;//获取考试类型
            TLP.ITestType = paper.ITestType;//获取考核方式
            TLP.ITotal = paper.ITotal;//获取试卷的总分
            TLP.IOverTime = paper.IOverTime;  //测试的总时间
            TLP.IHardlevel = paper.IHardlevel;//获取试卷的难易度
            TLP.IDiff = paper.IDiff; //获取试卷的区分度 
            TLP.DTestTime = paper.DTestTime;//获取试卷的测试时间
            TLP.DCreateTime = paper.DCreateTime;//获取试卷的创建时间
            TLP.ICourseId = paper.ICourseId;  //获取所属课程的ID
            TLP.ITeaId = frontCurrentTea.GetUserID(); //获取当前教师的id
            TLP.STeaCode = frontCurrentTea.GetNo();//获取当前教师的教师工号
            TLP.STeaName = frontCurrentTea.GetUserName();//获取当前教师的姓名
            TLP.IIsOk = 0;//默认未通过审核
            string id = paper.ICourseId.ToString();
            int ID = int.Parse(id);
            TbDeanCourse tempCourse = new DeanCourseDAO().GetByID(ID);  //在课程表中找该id下的课程
            if (tempCourse != null)
            {
                TLP.SCouseCode = tempCourse.SCourseCode;  //取得该课程的课程编号
            }


            //TODO
            // 还有一些属性没有加载 学年学期ID和IP



            TLPDao.Insert(TLP);

            frontCurrentTea.SetCurrentPaperID(TLP.Id);  //把当前试卷的ID放到session中

            TbTestPaperStrategy TS1 = new TbTestPaperStrategy();
            TS1.IPaperId = frontCurrentTea.GetCurrentPaperID();
            TS1.STitle = "策略一";   //设置默认的策略标题
            TS1.INum = 10;       //设置默认的“小题数量”为10道
            TS1.IProblemType = 1;//设置默认的题型为“单选题”
            TS1.IScore = 10; //设置默认该策略的总分为10分
            TS1.IAddBracket = 1; //默认给每一个大题下的小题加上括号
            TbTestPaperStrategy TS2 = new TbTestPaperStrategy();
            TS2.IPaperId = frontCurrentTea.GetCurrentPaperID();
            TS2.STitle = "策略二"; //设置默认的策略标题
            TS2.INum = 10;       //设置默认的“小题数量”为10道
            TS2.IProblemType = 3;//设置默认的题型为“判断题”
            TS2.IScore = 10; //设置默认该策略的总分为10分
            TS2.IAddBracket = 1; //默认给每一个大题下的小题加上括号

            TPSPDao.Insert(TS1);
            TPSPDao.Insert(TS2);

            return Json(TLP, JsonRequestBehavior.AllowGet);  //返回试卷的基本信息

        }

        /// <summary>
        /// 更新试卷的基本信息  add 9.13
        /// </summary>
        /// <param name="paper"></param>
        /// <returns></returns>
        public JsonResult GenUpdatePaper(TbTestLibPaper paper)
        {
            TbTestLibPaper tempPaper = new TestLibPaperDAO().GetByID(paper.Id);
            if (tempPaper != null)
            {
                tempPaper.STestName = paper.STestName;  //获取试卷的名称
                tempPaper.IKsType = paper.IKsType;//获取考试类型
                tempPaper.ITestType = paper.ITestType;//获取考核方式
                tempPaper.ITotal = paper.ITotal;//获取试卷的总分
                tempPaper.IHardlevel = paper.IHardlevel;//获取试卷的难易度
                tempPaper.IDiff = paper.IDiff; //获取试卷的区分度 
                tempPaper.IIsOk = 0; //设置默认未通过审核
                tempPaper.IOverTime = paper.IOverTime;  //测试的总时间
                tempPaper.DCreateTime = paper.DCreateTime;//获取试卷的创建时间
                tempPaper.ICourseId = paper.ICourseId;  //获取所属课程的ID
                tempPaper.ITeaId = frontCurrentTea.GetUserID(); //获取当前教师的id
                tempPaper.STeaCode = frontCurrentTea.GetNo();//获取当前教师的教师工号
                tempPaper.STeaName = frontCurrentTea.GetUserName();//获取当前教师的姓名

                string id = paper.ICourseId.ToString();
                int ID = int.Parse(id);
                TbDeanCourse tempCourse = new DeanCourseDAO().GetByID(ID);  //在课程表中找该id下的课程
                if (tempCourse != null)
                {
                    tempPaper.SCouseCode = tempCourse.SCourseCode;  //取得该课程的课程编号
                }
                TLPDao.Update(tempPaper);
                return Json(tempPaper, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 查询策略模板
        /// </summary>
        /// <returns></returns>
        public JsonResult StratgeTemplate()
        {
            string WhereClause = "I_PaperID=" + frontCurrentTea.GetCurrentPaperID();
            TList<TbTestPaperStrategy> tempStrategyList = new TestPaperStrategyDAO().GetByPage(WhereClause, 0, int.MaxValue);

            if (tempStrategyList.Count > 0)
            {
                return Json(tempStrategyList, JsonRequestBehavior.AllowGet);
            }

            return null;
        }



        /// <summary>
        /// 新增策略
        /// </summary>
        public void AddStrategy()
        {

            TbTestPaperStrategy tempStrategy = new TbTestPaperStrategy();
            tempStrategy.IPaperId = frontCurrentTea.GetCurrentPaperID();//获取当前试卷的Id
            tempStrategy.STitle = "新增策略"; //设置默认的策略标题
            tempStrategy.IScore = 10;//设置默认该策略的总分为10分
            tempStrategy.IProblemType = 1;//设置默认的题型为“单选题”
            tempStrategy.INum = 10;       //设置默认的“小题数量”为10道
            tempStrategy.IAddBracket = 1; //默认加括号
            TPSPDao.Insert(tempStrategy);


        }

        /// <summary>
        /// 删除策略
        /// </summary>
        /// <param name="id">策略的ID</param>
        public void DeleteStrategy(int id)
        {
            TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(id);
            if (tempStrategy != null)
            {
                TPSPDao.Del(tempStrategy);
            }

        }


        /// <summary>
        /// 更新策略标题
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        public void UpdateSTitle(string name, string value, int pk)
        {


            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("出错了,策略标题不能是空白！");
                return;
            }
            else
            {
                if (pk > 0)
                {


                    TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(pk);
                    if (tempStrategy != null)
                    {
                        tempStrategy.STitle = value;  //更新策略的策略标题
                        TPSPDao.Update(tempStrategy);
                    }

                }
            }


        }



        /// <summary>
        /// 更新策略的大题分数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        public void UpdateIScore(string name, string value, int pk)
        {


            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("出错了,策略的大题分数不能是空白！");
                return;
            }
            else
            {
                if (pk > 0)
                {


                    TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(pk);
                    if (tempStrategy != null)
                    {
                        int Value = int.Parse(value);
                        tempStrategy.IScore = Value;  // 更新策略的大题总分
                        TPSPDao.Update(tempStrategy);
                    }

                }
            }


        }
        /// <summary>
        /// 是否加括号
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        public void AddBracket(string name, string value, int pk)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("出错了！");
                return;
            }
            else
            {
                if (pk > 0)
                {

                    TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(pk);
                    if (tempStrategy != null)
                    {
                        int Value = int.Parse(value);
                        tempStrategy.IAddBracket = Value;  //更新策略括号
                        TPSPDao.Update(tempStrategy);
                    }

                }


            }

        }

        /// <summary>
        /// 更新策略的小题个数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        public void UpdateINum(string name, string value, int pk)
        {


            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("出错了,策略的大题分数不能是空白！");
                return;
            }
            else
            {
                if (pk > 0)
                {


                    TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(pk);
                    if (tempStrategy != null)
                    {
                        int Value = int.Parse(value);
                        tempStrategy.INum = Value;   //更新策略的小题数量
                        TPSPDao.Update(tempStrategy);
                    }

                }
            }


        }




        /// <summary>
        /// 更新策略的试题类型，且试题的类型不能重复，需要在前台进行验证
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        public void UpdateIProblemType(string name, string value, int pk)
        {


            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("出错了,策略的题型不能是空白！");
                return;
            }
            else
            {
                if (pk > 0)
                {

                    TbTestPaperStrategy tempStrategy = new TestPaperStrategyDAO().GetByID(pk);
                    if (tempStrategy != null)
                    {
                        int Value = int.Parse(value);
                        tempStrategy.IProblemType = Value;  //更新策略的试题类型
                        TPSPDao.Update(tempStrategy);
                    }

                }


            }

        }



        /// <summary>
        /// 查找试卷的策略信息
        /// </summary>
        /// <param name="PaperID">试卷的ID</param>
        /// <returns>返回试卷的策略个数</returns>
        public JsonResult GetTestPaperStrategy(int PaperID)
        {

            int Count;  //保存策略个数
            string WhereClause = "I_PaperID=" + PaperID;  //在策略表中查询试卷的策略
            TList<TbTestPaperStrategy> tempStrategy = new TestPaperStrategyDAO().GetByPage(WhereClause, 0, int.MaxValue);


            if (tempStrategy.Count > 0)   //存在该试卷的策略
            {
                Count = tempStrategy.Count;
                return Json(Count, JsonRequestBehavior.AllowGet);//返回策略的个数

            }
            else
                return null;
        }

        /// <summary>
        /// 换试题(针对试卷中个别不合理的小题进行筛选替换)
        /// </summary>
        /// <param name="paperdetailid">被换试题所对应TestLibPaperDetail表的ID</param>
        /// <param name="libid">新选择的试题的ID</param>
        public void ChangeQuestion(int paperdetailid, int libid, int StrategyID)
        {
            string whereClause = "I_StrategyID=" + StrategyID + " and I_LibID=" + paperdetailid;
            TList<TbTestLibPaperDetail> tempDetail = new TestLibPaperDetailDAO().GetByPage(whereClause, 0, int.MaxValue);
            if (tempDetail.Count > 0)
            {
                tempDetail[0].ILibId = libid;
                TLDDao.Update(tempDetail[0]);
            }

        }

        #region by lzq 10.17
        /// <summary>
        /// 出题
        /// </summary>
        public JsonResult CreatePaper(int paperId)
        {
            //int paperId = int.Parse(paperID);
            List<TList<TbTestLib>> paperLibList = new List<TList<TbTestLib>>();//存储课程所有需要的题

            int courseId = (int)new TestLibPaperDAO().GetByID(paperId).ICourseId;//当前课程编号
            TestLibPaperDetailDAO paperDetailDAO = new TestLibPaperDetailDAO();//试卷小题
            TestLibDAO testLibDAO = new TestLibDAO();//题库
            //取出课程所需的所有策略
            TList<TbTestPaperStrategy> strategyTotal = new TestPaperStrategyDAO().GetByPage("I_PaperID=" + paperId, 0, int.MaxValue);

            //检测需求题数是否超过题库中的题数
            foreach (var item in strategyTotal)
            {
                //查找该课程下的符合题型要求的所有题
                TList<TbTestLib> libTemp = testLibDAO.GetByPage(
                    "I_CousreID=" + courseId + "  and  I_ProblemType =" + item.IProblemType, 0, int.MaxValue);
                //需求题数超过题库中的题数,结束程序，前台给出提示
                if (libTemp.Count < item.INum)
                {
                    return Json(item.IProblemType);
                }

                //添加，后抽题用

                paperLibList.Add(libTemp);
            }
            //检测完毕
            int importent = 0;//章节重要度的和
            //该课程所有章节
            TList<TbTeaCatalog> catalog = new TeaCatalogDAO().GetByPage(
                "I_DeanCourseID=" + courseId + " and I_ParentID != 0", 0, int.MaxValue);
            foreach (var item in catalog)
            {
                importent = importent + (int)item.IImportance;
            }
            //根据策略，抽题
            for (int i = 0; i < paperLibList.Count; i++)
            {
                TList<TbTestLib> strateryList = paperLibList[i];//当期策略下的所有题
                int strateryId = strategyTotal[i].Id;//当期策略Id
                int paperStra = (int)strategyTotal[i].INum;//试卷需要的策略下的题目数
                int score = (int)strategyTotal[i].IScore / paperStra;//该策略下每到小题分数

                int complete = 0;//该策略已抽个数
                //从每个章节中抽题
                foreach (var item in catalog)
                {
                    TList<TbTestLib> tempList = new TList<TbTestLib>();
                    //从该策略下选出该章节题目
                    foreach (var item1 in strateryList)
                    {
                        if (item1.ITeaCatalog == item.Id)
                        {
                            tempList.Add(item1);
                        }
                    }
                    //题目选完
                    //计算当期章节需要题目
                    double x = (double)item.IImportance / importent;
                    int number = GetInt(paperStra * x);
                    //章节需求题目比题库中的题目多，则将题库中所有题目添加进去，差的题后面补

                    int type;//当前策略所抽题型
                    if (number > tempList.Count) { number = tempList.Count; }
                    //循环抽题
                    Random ran = new Random(unchecked((int)DateTime.Now.Ticks));
                    for (int j = 0; j < number; j++)
                    {
                        TbTestLibPaperDetail detailTemp = new TbTestLibPaperDetail();
                        int n = ran.Next(0, tempList.Count);
                        TbTestLib lib = tempList[n];
                        detailTemp.ILibId = lib.Id;
                        detailTemp.ILibType = lib.IProblemType;
                        type = (int)lib.IProblemType;
                        detailTemp.IStrategyId = strateryId;
                        detailTemp.IScore = score;
                        paperDetailDAO.Insert(detailTemp);
                        tempList.Remove(lib);//题目添加到试卷后,从list去掉该题，防止重复
                        strateryList.Remove(lib);
                        complete++;
                    }
                    //循环抽题结束
                }
                //章节抽题完
                //若该策略没抽满，从剩下的题中随机抽题
                Random ran1 = new Random(unchecked((int)DateTime.Now.Ticks));
                int difference = paperStra - complete;

                if (difference > 0)
                {
                    //循环剩下的题目数量
                    for (int k = 0; k < paperStra - complete; k++)
                    {
                        TbTestLibPaperDetail detailTemp = new TbTestLibPaperDetail();
                        int n = ran1.Next(0, strateryList.Count);
                        TbTestLib lib = strateryList[n];
                        detailTemp.ILibId = lib.Id;
                        detailTemp.ILibType = lib.IProblemType;
                        detailTemp.IStrategyId = strateryId;
                        detailTemp.IScore = score;
                        paperDetailDAO.Insert(detailTemp);
                        strateryList.Remove(lib);//题目添加到试卷后,从list去掉该题，防止重复                 
                    }
                }
                if (difference < 0)
                {
                    int dif = 0 - difference;
                    TList<TbTestLibPaperDetail> deTmp = TLDDao.GetByPage(
                        "I_StrategyID=" + strateryId, 0, int.MaxValue);
                    TList<TbTestLibPaperDetail> delete = new TList<TbTestLibPaperDetail>();
                    for (int k = 0; k < dif; k++)
                    {
                        int n = ran1.Next(0, deTmp.Count);
                        delete.Add(deTmp[n]);
                    }
                    TLDDao.Del(delete);
                }
            }
            //策略抽题完
            return Json("-1");
        }

        //四舍五入
        public int GetInt(double x)
        {
            x = x + 0.5;
            return (int)x;
        }

        // 导出试卷
        public FileStreamResult ExportWord(int paperId)
        {
            string url = "";//返回的url

            const string titlePath = "/Upload/paper/titleTemplate.doc";////试卷模版
            const string detailPath = "/Upload/paper/paperDetail.doc";//试卷模版


            DocumentBuilder detailDB;
            int straChNo = 0;     //大题中文题号
            int Total = 0;//试卷总分

            int TermId = 1;//学期ID

            Document titleDoc = new Document(Server.MapPath(titlePath)); //载入模板
            Document detailDoc = new Document(Server.MapPath(detailPath)); //载入模板
            string[] strNo = { "一、", "二、", "三、", "四、", "五、", "六、", "七、", "八、", "九、", "十、" };   //大题编号
            string[] Option = { "A.", "B.", "C.", "D.", "E.", "F.", "G." };//小题选项
            string classNameStr = "";//考试班级
            //取得试卷信息
            TbTestLibPaper paper = TLPDao.GetByID(paperId);
            string paperName = string.IsNullOrEmpty(paper.STestName) ? " " : paper.STestName;
            //试卷所有策略
            TList<TbTestPaperStrategy> tempStrategy = new TestPaperStrategyDAO().GetByPage("I_PaperID=" + paperId, 0, int.MaxValue);
            //做试卷开头
            Dictionary<string, string> dictSource = new Dictionary<string, string>();

            dictSource.Add("TestName", paperName);//替换考试名字
            if (!string.IsNullOrEmpty(paper.STermName))
            {
                dictSource.Add("TermName", paper.STermName);//替换学期名字
            }
            else
            {
                dictSource.Add("TermName", "                 ");//替换学期名字
            }
            //paper.ITestType
            string type1 = "";
            string type2 = "";
            if (paper.ITestType == 1)
            {
                type1 = "√";
                type2 = "  ";
            }
            else
            {
                type2 = "√";
                type1 = "  ";
            }
            dictSource.Add("Type1", type1);
            dictSource.Add("Type2", type2);//替换试卷类型
            //paper.ITestType

            List<TbDeanStuSelCourse> className = new ExamController().GetClassList(paper.STeaCode, (int)paper.ICourseId, TermId);
            foreach (var item in className)
            {
                classNameStr = classNameStr + "," + item.SClassName;
            }
            classNameStr = classNameStr.Substring(1);
            dictSource.Add("ClassName", classNameStr);//替换试卷班级
            //试卷标题中的分数
            for (int i = 0; i < tempStrategy.Count; i++)
            {
                int j = i + 1;
                string no = "N" + j;
                dictSource.Add(no, tempStrategy[i].IScore.ToString());
                Total += (int)tempStrategy[i].IScore;
            }
            //若策略不够，把其他策略分数段置空
            if (tempStrategy.Count < 8)
            {
                int tCount = 8 - tempStrategy.Count;
                for (int i = 0; i < tCount; i++)
                {
                    int j = tempStrategy.Count + i + 1;
                    string no = "N" + j;
                    dictSource.Add(no, " ");
                }
            }
            dictSource.Add("Total", Total.ToString());//替换试卷总分

            foreach (string name in dictSource.Keys)
            {
                titleDoc.Range.Replace(name, dictSource[name], true, true);
            }



            //做试卷内容
            detailDB = new DocumentBuilder(detailDoc);
            detailDB.ParagraphFormat.Alignment = ParagraphAlignment.Left;//左对齐
            detailDB.Font.Name = "宋体";

            // 1.写入试卷大题（策略表）
            foreach (var itemStra in tempStrategy)
            {
                detailDB.Font.Size = 10;//大题题目字体大小
                detailDB.Font.Bold = true;//大题题目字体大小
                int deNo = 1; //小题标号              
                int totalCount = (int)itemStra.IScore;//大题的总分 
                int totalNum = (int)itemStra.INum;//小题数量
                int perScore = totalCount / totalNum;//每小题的平均分
                string strBracket = itemStra.IAddBracket == 1 ? "(  )" : "";//是否加括号Bracket
                string titleStr = strNo[straChNo] + itemStra.STitle +
                    "(本大题共 " + totalNum + "小题，每小题" + perScore + "分，共" + totalCount + "分)";
                detailDB.Writeln(titleStr);//将大题题目写入到word



                //读取大题下的小题
                TList<TbTestLibPaperDetail> tempDetail = TLDDao.GetByPage("I_StrategyID=" + itemStra.Id, 0, int.MaxValue);
                foreach (var itemDetail in tempDetail)
                {
                    detailDB.Font.Size = 9;//小题题目字体大小
                    detailDB.Font.Bold = false;//小题题目字体大小
                    int optionNo = 0;//小题选项编号
                    TbTestLib tempLib = TibDao.GetByID((int)itemDetail.ILibId);
                    string temp = deNo + "." + tempLib.STitle + strBracket;//拼装题目内容
                    detailDB.Writeln(temp);//将小题题目写入到word
                    //读取选项,不读判断题
                    if (itemDetail.ILibType != 3)
                    {
                        TList<TbTestLibOption> optionTemp = optionDao.GetByPage("I_LibID=" + itemDetail.ILibId, 0, int.MaxValue);
                        foreach (var itemOption in optionTemp)
                        {
                            string opStr = Option[optionNo] + itemOption.SOptionName;
                            detailDB.Writeln(opStr);//将小题选项写入到word
                            optionNo++;//选项编号加1
                        }
                    }
                    deNo++;//小题题号加1
                    detailDB.InsertBreak(BreakType.LineBreak);
                }
                //读取大题下的小题 END

                //大题题号加1
                straChNo++;
            }

            appendDoc(titleDoc, detailDoc, false);
            url = Server.MapPath(paperPath + paperName + ".doc");
            titleDoc.Save(url, Aspose.Words.SaveFormat.Docx);//保存

            return File(new FileStream(url, FileMode.Open), "application/octet-stream", Server.UrlEncode(paperName + ".doc"));
        }

        //从word最后一段开始修改
        public static void appendDoc(Document dstDoc, Document srcDoc, bool includeSection)
        {
            if (includeSection)
            {
                foreach (Section srcSection in srcDoc.Sections)
                {
                    Node dstNode = dstDoc.ImportNode(srcSection, true, ImportFormatMode.UseDestinationStyles);
                    dstDoc.AppendChild(dstNode);
                }
            }
            else
            {
                Node node = dstDoc.LastSection.Body.LastParagraph;

                if (node == null)
                {
                    node = new Aspose.Words.Paragraph(srcDoc);
                    dstDoc.LastSection.Body.AppendChild(node);
                }

                if ((node.NodeType != NodeType.Paragraph)
                    & (node.NodeType != NodeType.Table))
                {
                    throw new Exception("Use appendDoc(dstDoc, srcDoc, true) instead of appendDoc(dstDoc, srcDoc, false)");
                }
                insertDocumentAfterNode(node, dstDoc, srcDoc);
            }
        }
        public static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc)
        {
            CompositeNode dstStory = insertAfterNode.ParentNode;

            NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KeepSourceFormatting);

            int sectCount = srcDoc.Sections.Count;

            for (int sectIndex = 0; sectIndex < sectCount; sectIndex++)
            {
                Section srcSection = srcDoc.Sections[sectIndex];
                int nodeCount = srcSection.Body.ChildNodes.Count;
                for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
                {
                    Node srcNode = srcSection.Body.ChildNodes[nodeIndex];
                    Node newNode = importer.ImportNode(srcNode, true);
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }

        }

        #endregion

    }
}
